package logic

import (
	"classtype/classtype"
	"classtype/global/model"
	"classtype/internal/svc"
	"context"
	"encoding/json"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ClassTypeFindLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewClassTypeFindLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassTypeFindLogic {
	return &ClassTypeFindLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ClassTypeFindLogic) ClassTypeFind(in *classtype.ClassTypeFindRequest) (*classtype.ClassTypeFindResponse, error) {
	// todo: add your logic here and delete this line
	key := "tree"
	var Res []*classtype.ClassTypeTree
	data := model.RDB.Get(model.Ctx, key).Val()
	if data != "" {
		json.Unmarshal([]byte(data), &Res)
	} else {
		types := model.ClassTypes{}
		tree, err := types.BuildTree()
		if err != nil {
			return nil, err
		}
		Res = tree
		data, _ := json.Marshal(tree)
		model.RDB.Set(model.Ctx, key, string(data), 10*time.Minute)
	}
	return &classtype.ClassTypeFindResponse{
		ClassTypeTree: Res,
	}, nil
}
